import { DeleteOutlined, ReloadOutlined } from "@ant-design/icons"
import { pageType, questionnaireType } from "@/types"
import { http } from "@/utils/http"
import { Button, message, Popconfirm, Spin, Table } from "antd"
import { ColumnsType } from "antd/lib/table"
import React, { useEffect, useState } from "react"

const DataPanel: React.FC = () => {
  const [questionnaireList, setQuestionnaireList] = useState<questionnaireType[]>([])
  const [pageState, setPageState] = useState<pageType>({ pages: 0, total: 0, paramsData: { currentPage: 1, pageSize: 128 } })
  const [pageSize, setPageSize] = useState(8)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [isLoading, setIsLoading] = useState(false)

  const columns: ColumnsType<questionnaireType> = [
    {
      title: "问卷编号",
      dataIndex: "questionnaire_number",
      key: "questionnaire_number",
    },
    {
      title: "调研日期",
      dataIndex: "researchDate",
      key: "researchDate",
      align: "center",
      sorter: (a, b) => {
        const aTime = new Date(a.researchDate).getTime()
        const bTime = new Date(b.researchDate).getTime()
        return aTime - bTime
      },
    },
    {
      title: "贫困型家庭",
      dataIndex: "isHomeStyle",
      key: "isHomeStyle",
      align: "center",
      render: (isHomeStyle) => (isHomeStyle ? "是" : "否"),
      filters: [
        { text: "是", value: true },
        { text: "否", value: false },
      ],
      onFilter: (value, questionnaire) => questionnaire.isHomeStyle === value,
    },
    {
      title: "户口",
      dataIndex: "isCity",
      key: "isCity",
      align: "center",
      render: (isCity: number) => (isCity === 1 ? "农村" : "城镇"),
      filters: [
        { text: "城镇", value: 0 },
        { text: "农村", value: 1 },
      ],
      onFilter: (value, questionnaire) => questionnaire.isCity === value,
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "年龄",
      dataIndex: "user_age",
      key: "user_age",
      align: "center",
      sorter: (a, b) => a.user_age - b.user_age,
    },
    {
      title: "性别",
      dataIndex: "user_sex",
      key: "user_sex",
      align: "center",
      filters: [
        { text: "男", value: "男" },
        { text: "女", value: "女" },
      ],
      onFilter: (value, questionnaire) => questionnaire.user_sex === value,
    },
    {
      title: "身份证",
      align: "center",
      dataIndex: "idCard",
      key: "idCard",
    },
    {
      title: "手机号码",
      dataIndex: "phoneNumber",
      key: "phoneNumber",
      align: "center",
    },
    {
      title: "所在市",
      dataIndex: "city",
      key: "city",
      align: "center",
    },
    {
      title: "县/区",
      dataIndex: "county",
      key: "county",
      align: "center",
    },
    {
      title: "镇/街办",
      dataIndex: "town",
      key: "town",
      align: "center",
    },
    {
      title: "所在村",
      dataIndex: "village",
      key: "village",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      key: "112",
      render: (questionnaire: questionnaireType) => {
        return (
          <Popconfirm
            title="确认删除该条数据吗"
            placement="topRight"
            cancelText="取消"
            okText="确定"
            onConfirm={() => deleteQuestionnaire(questionnaire.questionnaire_id)}
          >
            <Button type="primary" shape="circle" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        )
      },
    },
  ]

  useEffect(() => {
    getQuestionnaireList()
  }, [])

  /**
   * 获取问卷列表
   */
  const getQuestionnaireList = async () => {
    const { data: res } = await http.get(`/get/basicInfo?currentPage=${1}&pageSize=${128}`)
    setQuestionnaireList(res.data.list)
    setPageState({
      pages: res.data.pages,
      total: res.data.total,
      paramsData: { currentPage: 2, pageSize: 128 },
    })
  }

  /**
   * 加载更多
   * @returns
   */
  const loadMore = async () => {
    if (questionnaireList.length === pageState.total) return message.warning("没有更多了")
    const { currentPage, pageSize } = pageState.paramsData
    const { data: res } = await http.get(`/get/basicInfo?currentPage=${currentPage}&pageSize=${pageSize}`)
    setQuestionnaireList([...questionnaireList, ...res.data.list])
    setPageState({
      pages: res.data.pages,
      total: res.data.total,
      paramsData: { currentPage: currentPage + 1, pageSize: 128 },
    })
  }

  /**
   * 根据questionnaire_id删除某条问卷记录
   * @param questionnaire_id 问卷id
   */
  const deleteQuestionnaire = async (questionnaire_id: string | number) => {
    const res = await http.delete(`/basicInfo?questionnaire_id=${questionnaire_id}`)
    if (res.status !== 200) return message.error("删除失败")
    getQuestionnaireList()
    message.success("删除成功")
  }

  /**
   * 选中导出
   */
  const selectedExportToExcel = async () => {
    if (selectedRowKeys.length === 0) return message.warning("未选择")
    try {
      setIsLoading(true)
      const { data: res } = await http.post("/exportManySheet", { ids: selectedRowKeys }, { responseType: "blob" })
      const blob = new Blob([res], { type: "application/vnd.ms-excel" })
      const link = document.createElement("a")
      link.href = window.URL.createObjectURL(blob)
      link.download = "问卷表.xlsx"

      // 元素添加至body，兼容firefox
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch {
      message.error("服务器异常")
    } finally {
      setIsLoading(false)
    }
  }

  /**
   * 一键导出
   */
  const defaultExportToExcel = async () => {
    try {
      setIsLoading(true)
      const allRowKeys = questionnaireList.map((questionnaire) => questionnaire.questionnaire_id)
      const { data: res } = await http.post("/exportManySheet", { ids: allRowKeys }, { responseType: "blob" })
      const blob = new Blob([res], { type: "application/vnd.ms-excel" })
      const link = document.createElement("a")
      link.href = window.URL.createObjectURL(blob)
      link.download = "问卷表.xlsx"

      // 元素添加至body，兼容firefox
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } catch (err) {
      message.error("服务器异常")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Spin spinning={isLoading} tip="正在导出，可能需要一点时间..." size="large">
      <header style={{ marginBottom: 20, display: "flex" }}>
        <Button type="primary" style={{ marginRight: 20 }} danger onClick={defaultExportToExcel}>
          一键导出
        </Button>
        <Button type="primary" onClick={selectedExportToExcel}>
          选中导出
        </Button>
        <Button type="primary" icon={<ReloadOutlined />} style={{ marginLeft: "auto" }} onClick={loadMore}>
          加载更多
        </Button>
      </header>

      <Table
        size="small"
        dataSource={questionnaireList}
        rowSelection={{ checkStrictly: true, onChange: (selectedRowKeys) => setSelectedRowKeys(selectedRowKeys) }}
        rowKey={(questionnaire) => questionnaire.questionnaire_id}
        columns={columns}
        pagination={{ pageSize: pageSize, pageSizeOptions: [8, 10, 20, 50], onChange: (_, pageSize) => setPageSize(pageSize) }}
        style={{ minWidth: 1200 }}
      />
    </Spin>
  )
}

export default DataPanel
